package wwy.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import wwy.Common.LogicService;
import wwy.Dao.UserDao;
import wwy.Dto.RegisterDto;
import wwy.Dto.UserDto;
import wwy.entity.User;

@Service
public class UserService extends LogicService<UserDao, User, Long> {
    private final RoleService roleService;
    public UserService(@Autowired UserDao dao, RoleService roleService){
        super(dao);this.roleService = roleService;}

    @Transactional
    public UserDto getUserInfo(String phone, String password){
        User user = dao.findByPhoneAndPassWord(phone, DigestUtils.md5DigestAsHex(password.getBytes()));
        if(user == null) return null;
        return modelMapper.map(user,UserDto.class);
    }

    @Transactional
    public User GetUserByUserName(String userName){
        return dao.findByUserName(userName);
    }
    @Transactional
    public UserDto getUserById(Long userId) {
        return modelMapper.map(dao.getReferenceById(userId),UserDto.class);
    }
    @Transactional
    public String addNewUser(RegisterDto userInfo){
        User user = modelMapper.map(userInfo,User.class);
        user.setRole(roleService.getRoleByName("user"));
        dao.save(user);
        return "success";
    }

    //添加默认用户
    @Transactional
    @EventListener(ApplicationReadyEvent.class)
    @Order(2)
    public void addDefaultUser(){
        if (dao.count() > 0) return;
        User user = new User();
        user.setUserName("admin");
        user.setPassword("123456");
        user.setSex("男");
        user.setPhone("123456789");
        user.setRole(roleService.getRoleByName("admin"));
        dao.save(user);

        User user1 = new User();
        user1.setUserName("user1");
        user1.setPassword("123");
        user1.setSex("女");
        user1.setPhone("123456789");
        user1.setRole(roleService.getRoleByName("user"));
        dao.save(user1);

        User user2 = new User();
        user2.setUserName("user2");
        user2.setPassword("123");
        user2.setSex("男");
        user2.setPhone("123");
        user2.setRole(roleService.getRoleByName("user"));
        dao.save(user2);
    }
}
